package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.constant.IBusinessConstant;
import com.ruoyi.business.domain.SysFunction;
import com.ruoyi.business.domain.TenantFunctionComposite;
import com.ruoyi.business.domain.TenantFunctionParametersVersion;
import com.ruoyi.business.domain.TenantFunctionVersion;
import com.ruoyi.business.mapper.TenantFunctionVersionMapper;
import com.ruoyi.business.service.ISysFunctionService;
import com.ruoyi.business.service.ITenantFunctionVersionService;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 租户组件功能点版本表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-18
 */
@Slf4j
@Service
public class TenantFunctionVersionServiceImpl implements ITenantFunctionVersionService
{
    @Autowired
    private TenantFunctionVersionMapper tenantFunctionVersionMapper;
    @Autowired
    private ISysFunctionService sysFunctionService;
    /**
     * 查询租户组件功能点版本表
     *
     * @param id 租户组件功能点版本表主键
     * @return 租户组件功能点版本表
     */
    @Override
    public TenantFunctionVersion selectTenantFunctionVersionById(Long id)
    {
        return tenantFunctionVersionMapper.selectTenantFunctionVersionById(id);
    }

    /**
     * 查询租户组件功能点版本表列表
     *
     * @param tenantFunctionVersion 租户组件功能点版本表
     * @return 租户组件功能点版本表
     */
    @Override
    public List<TenantFunctionVersion> selectTenantFunctionVersionList(TenantFunctionVersion tenantFunctionVersion)
    {
        return tenantFunctionVersionMapper.selectTenantFunctionVersionList(tenantFunctionVersion);
    }

    /**
     * 新增租户组件功能点版本表
     *
     * @param tenantFunctionVersion 租户组件功能点版本表
     * @return 结果
     */
    @Override
    public int insertTenantFunctionVersion(TenantFunctionVersion tenantFunctionVersion)
    {
        tenantFunctionVersion.setCreateTime(DateUtils.getNowDate());
        // 1. 反转义（恢复 > 等符号）
        String rawScript = tenantFunctionVersion.getDesignScript().replace("&gt;", ">")
                .replace("&lt;", "<")
                .replace("&amp;", "&");
        tenantFunctionVersion.setDesignScript(rawScript);
        return tenantFunctionVersionMapper.insertTenantFunctionVersion(tenantFunctionVersion);
    }

    /**
     * 修改租户组件功能点版本表
     *
     * @param tenantFunctionVersion 租户组件功能点版本表
     * @return 结果
     */
    @Override
    public int updateTenantFunctionVersion(TenantFunctionVersion tenantFunctionVersion)
    {
        tenantFunctionVersion.setUpdateTime(DateUtils.getNowDate());
        // 1. 反转义（恢复 > 等符号）
        String rawScript = tenantFunctionVersion.getDesignScript().replace("&gt;", ">")
                .replace("&lt;", "<")
                .replace("&amp;", "&");
        tenantFunctionVersion.setDesignScript(rawScript);
        return tenantFunctionVersionMapper.updateTenantFunctionVersion(tenantFunctionVersion);
    }

    /**
     * 批量删除租户组件功能点版本表
     *
     * @param ids 需要删除的租户组件功能点版本表主键
     * @return 结果
     */
    @Override
    public int deleteTenantFunctionVersionByIds(Long[] ids)
    {
        return tenantFunctionVersionMapper.deleteTenantFunctionVersionByIds(ids);
    }

    /**
     * 删除租户组件功能点版本表信息
     *
     * @param id 租户组件功能点版本表主键
     * @return 结果
     */
    @Override
    public int deleteTenantFunctionVersionById(Long id)
    {
        return tenantFunctionVersionMapper.deleteTenantFunctionVersionById(id);
    }

    /**
     * 更新版本为非当前版本
     *
     * @param functionCode   功能编码
     * @param enterpriseCode 租户编码
     * @return
     */
    @Override
    public int updateCurrentVersionToIsNot(String functionCode, String enterpriseCode) {
        return tenantFunctionVersionMapper.updateCurrentVersionToIsNot(functionCode, enterpriseCode);
    }

    /**
     * 翻译设计脚本（json）为groovy源代码
     *
     * @param tenantFunctionComposite
     * @return
     */
    @Override
    public String makeGroovySource(TenantFunctionComposite tenantFunctionComposite) {
        String jsonStr = tenantFunctionComposite.getTenantFunctionVersion().getDesignScript();
        JSONObject jsonObject = JSON.parseObject(jsonStr);

        // 1. 收集所有组件和菱形框
        Map<String, JSONObject> components = new HashMap<>();
        Map<String, JSONObject> diamonds = new HashMap<>();

        JSONArray svgElements = jsonObject.getJSONArray("svgElements");
        JSONArray diamondElements = jsonObject.getJSONArray("diamondElements");
        JSONArray connections = jsonObject.getJSONArray("connections");

        // 2. 索引所有元素
        indexElements(svgElements, components);
        indexElements(diamondElements, diamonds);

        // 提取所有子功能点groovy源码
        List<String> childGroovySource = pickChildGroovySource(svgElements);
        // 生成import段
        String importSegs = mergeOnlyImports(childGroovySource);

        // 3. 构建执行流程图
        StringBuilder groovy = new StringBuilder();
        groovy.append(importSegs);
        groovy.append("def ").append(tenantFunctionComposite.getTenantFunctionMain().getFunctionCode()).append("(").
                append(makeGroovyFunctionParams(tenantFunctionComposite.getTenantFunctionParametersVersions()))
                .append(")")
                .append(" {\n");

        // 4. 查找起始组件（无入连接的组件）
        Set<String> componentIds = new HashSet<>(components.keySet());
        String startComponentId = findStartComponent(connections, componentIds);
        if (startComponentId == null) {
            throw new RuntimeException("未找到起始组件");
        }
        //合并diamonds和components
        Map<String, JSONObject> allElements = new HashMap<>();
        allElements.putAll(components);
        allElements.putAll(diamonds);
        // 5. 检测循环和退出条件
        LoopAnalysisResult loopAnalysis = analyzeLoops(connections, allElements);

        // 6. 生成开始节点
        Set<String> processed = new HashSet<>();
        generateComponentCode(startComponentId, components, diamonds, connections,
                groovy, processed, loopAnalysis);

        groovy.append("}\n");
        return groovy.toString();
    }

    /**
     * 构造groovy函数参数
     * @param tenantFunctionParametersVersions
     * @return
     */
    private String makeGroovyFunctionParams(List<TenantFunctionParametersVersion> tenantFunctionParametersVersions) {
        StringBuilder params = new StringBuilder("");
        for(TenantFunctionParametersVersion tenantFunctionParametersVersion:tenantFunctionParametersVersions){
            params.append(tenantFunctionParametersVersion.getParameterName()).append(",");
        }
        return params.toString().isEmpty() ? "" :  params.substring(0, params.length() - 1) ;
    }

    // 循环分析结果类
    private static class LoopAnalysisResult {
        Set<String> loopStartPoints; // 循环起点组件ID
        Map<String, String> loopExitConditions; // 循环退出条件（组件ID -> 退出条件）
        Map<String, String> loopContinueConditions; // 循环继续条件（组件ID -> 继续条件）

        public LoopAnalysisResult() {
            this.loopStartPoints = new HashSet<>();
            this.loopExitConditions = new HashMap<>();
            this.loopContinueConditions = new HashMap<>();
        }
    }
    // 分析循环结构和退出条件
    private LoopAnalysisResult analyzeLoops(JSONArray connections, Map<String, JSONObject> components) {
        LoopAnalysisResult result = new LoopAnalysisResult();

        // 找出所有循环起点
        for (String componentId : components.keySet()) {
            if (isLoopStartPoint(connections, componentId)) {
                result.loopStartPoints.add(componentId);

                // 收集所有出向连接的条件
//                for (int i = 0; i < connections.size(); i++) {
//                    JSONObject conn = connections.getJSONObject(i);
//                    if (componentId.equals(conn.getString("startElementId"))) {
//                        String condition = conn.getString("condition");
//                        if (condition != null) {
//                            if (condition.startsWith("!")) {
//                                result.loopExitConditions.put(componentId, condition.substring(1));
//                            } else {
//                                result.loopContinueConditions.put(componentId, condition);
//                            }
//                        }
//                    }
//                }
            }
        }
        return result;
    }

    /**
     * 判断是否为循环起点
     * @param connections
     * @param componentId
     * @return
     */
    private boolean isLoopStartPoint(JSONArray connections, String componentId) {
        List<String> componentIds = new ArrayList<>();
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            if(conn.getString("id").equals("conn-1749043103982-fmw48z7p6")){
                log.info("conn id:"+conn.getString("id"));
            }
            String endElementId1 = conn.getString("endElementId");
            if (isLine(endElementId1)){
                endElementId1 = nestedFindNonLine(connections,endElementId1,true);
            }
            if (endElementId1.equals(componentId)) {
              log.info("match conn id:"+conn.getString("id"));
              //判断是否线条
              if(isLine(conn.getString("startElementId"))){
                //循环查找线条的非线条的终点（即菱形或组件）
                componentIds.add(nestedFindNonLine(connections,conn.getString("startElementId"),false));
              }else {
                  componentIds.add(conn.getString("startElementId"));
              }
              componentIds.add(componentId);
            }else {
                String startElementId = conn.getString("startElementId");
                if(isLine(startElementId)){
                    startElementId = nestedFindNonLine(connections,startElementId,false);
                }
                if (startElementId.equals(componentId)) {
                    log.info("match conn id:"+conn.getString("id"));
                    componentIds.add(componentId);
                    if(isLine(conn.getString("endElementId"))){
                        //循环查找线条的非线条的终点（即菱形或组件）
                        componentIds.add(nestedFindNonLine(connections,conn.getString("endElementId"),true));
                    }else {
                        componentIds.add(conn.getString("endElementId"));
                    }
                }
            }
            //循环开始点为componentIds最后一个元素的连线
            if(componentIds.size()>1){
                for(int j=i+1;j<connections.size();j++){
                    JSONObject conn1 = connections.getJSONObject(j);
                    if(conn1.getString("id").equals("conn-1748851712912-zqfxscgcd") && componentId.equals("diamond-1747904536570")){
                        log.info("conn id:"+conn1.getString("id"));
                    }
                    String startElementId1 = conn1.getString("startElementId");
                    if(isLine(startElementId1)){
                        startElementId1 = nestedFindNonLine(connections,startElementId1,false);
                    }
                    if(startElementId1.equals(componentIds.get(componentIds.size()-1))){
                        log.info("match conn id:"+conn1.getString("id"));
                        if(isLine(conn1.getString("endElementId"))){
                            //循环查找线条的非线条的终点（即菱形或组件）
                            String endElementId = nestedFindNonLine(connections, conn1.getString("endElementId"), true);
                            //紧挨endElementId相同不算
                            if(!componentIds.get(componentIds.size()-1).equals(endElementId)) {
                                componentIds.add(endElementId);
                            }
                        }else {
                            String endElementId = conn1.getString("endElementId");
                            //紧挨endElementId相同不算
                            if(!componentIds.get(componentIds.size()-1).equals(endElementId)) {
                                componentIds.add(endElementId);
                            }
                        }
                    }else{
                        String endElementId = conn1.getString("endElementId");
                        if(isLine(endElementId)){
                            //循环查找线条的非线条的终点（即菱形或组件）
                            endElementId = nestedFindNonLine(connections,endElementId,true);
                        }
                        if(endElementId.equals(componentIds.get(componentIds.size()-1))){
                            log.info("match conn id:"+conn1.getString("id"));
                            if(isLine(conn1.getString("startElementId"))){
                                //循环查找线条的非线条的终点（即菱形或组件）
                                String startElementId = nestedFindNonLine(connections, conn1.getString("startElementId"), false);
                                //紧挨elementId相同不算
                                if(!componentIds.get(componentIds.size()-1).equals(startElementId)) {
                                    componentIds.add(startElementId);
                                }
                            }else {
                                String startElementId = conn1.getString("startElementId");
                                //紧挨elementId相同不算
                                if(!componentIds.get(componentIds.size()-1).equals(startElementId)) {
                                    componentIds.add(startElementId);
                                }
                            }
                        }else{
                            //如果结束点等于componentId，且紧挨组件id不相同，则添加
                            if(endElementId.equals(componentId) && !componentIds.get(componentIds.size()-1).equals(endElementId)) {
                                componentIds.add(endElementId);
                            }
                        }
                    }
                    //判断componentIds是否出现两次
                    int count = Collections.frequency(componentIds, componentId);
                    if(count>=2){
                        return true;
                    }
                }
                return false;
            }
        }
        return false;
    }

    /**
     * 嵌套查询非线条的终点
     *
     * @param connections
     * @param startElementId
     * @param bEnd
     * @return
     */
    private String nestedFindNonLine(JSONArray connections, String startElementId, boolean bEnd) {
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            if (conn.getString("id").equals(startElementId)) {
                if (bEnd) {
                    if (isLine(conn.getString("endElementId"))) {
                        return nestedFindNonLine(connections, conn.getString("endElementId"), true);
                    } else {
                        return conn.getString("endElementId");
                    }
                } else {
                    if (isLine(conn.getString("startElementId"))) {
                        return nestedFindNonLine(connections, conn.getString("startElementId"), false);
                    } else {
                        return conn.getString("startElementId");
                    }
                }
            }
        }
        throw new RuntimeException("未找到对应的非线条对象");
    }

    /**
     * 判断是否为线条id
     * @param startElementId
     * @return
     */
    private boolean isLine(String startElementId) {
        return startElementId.startsWith("conn-");
    }
    // 检测循环起点（返回所有可能成为循环起点的组件ID）
// 检测循环起点（返回所有可能成为循环起点的组件ID）

    // 检查从startId到targetId是否有路径（深度优先搜索）
    private boolean hasPath(Map<String, List<String>> incomingMap, String currentId, String targetId, Set<String> visited) {
        if (currentId.equals(targetId)) return true;
        if (visited.contains(currentId)) return false;

        visited.add(currentId);
        List<String> predecessors = incomingMap.getOrDefault(currentId, Collections.emptyList());

        for (String pred : predecessors) {
            if (hasPath(incomingMap, pred, targetId, visited)) {
                return true;
            }
        }

        return false;
    }




    // 生成组件/菱形框的实际代码
    private void generateComponentBody(String elementId,
                                       Map<String, JSONObject> components,
                                       Map<String, JSONObject> diamonds,
                                       JSONArray connections,
                                       StringBuilder groovy,
                                       Set<String> processed,
                                       LoopAnalysisResult loopAnalysis) {
        if(elementId.equals("component-1748245258786-76rskbws7")){
            log.info("match component id:"+elementId);
        }
        if (processed.contains(elementId)) return;
        processed.add(elementId);

        // 处理组件
        if (components.containsKey(elementId)) {
            JSONObject component = components.get(elementId);
            String objectType = component.getString("objectType");
            if(IBusinessConstant.NODE_TYPE_COMPONENT.equals(objectType)) {
                JSONObject textAttrs = component.getJSONArray("children").getJSONObject(2).getJSONObject("attrs");

                String className = getSimpleClassName(textAttrs.getString("className"));
                String method = textAttrs.getString("selectedFunctionPoint");
                String returnVar = textAttrs.getString("returnValueName");
                JSONArray params = textAttrs.getJSONArray("functionPointParams");

                // 生成方法调用代码
                groovy.append("        // 组件: ").append(elementId).append("\n");
                if (StringUtils.isNotEmpty(returnVar)) {
                    groovy.append("        def ").append(returnVar).append(" = ");
                } else {
                    groovy.append("        ");
                }
                groovy.append(className).append(".").append(method).append("(");
                appendParams(groovy, params);
                groovy.append(")\n\n");

                // 处理出向连接
                processOutgoingConnections(elementId, components, diamonds, connections,
                        groovy, processed, loopAnalysis);
            } else if(IBusinessConstant.NODE_TYPE_RETURN.equals(objectType)){
                groovy.append("        // 节点: ").append(elementId).append("\n");
                String returnVar = component.getString("returnValue");
                groovy.append("        return ").append(returnVar).append("\n\n");
            }

        }
        // 处理菱形节点
        else if (diamonds.containsKey(elementId)) {
            // 收集所有出向连接
            List<JSONObject> outgoing = new ArrayList<>();
            for (int i = 0; i < connections.size(); i++) {
                JSONObject conn = connections.getJSONObject(i);
                if (elementId.equals(conn.getString("startElementId"))) {
                    outgoing.add(conn);
                }
            }

            // 生成条件分支
            boolean hasConditions = false;
            for (JSONObject conn : outgoing) {
                if (StringUtils.isNotEmpty(conn.getString("condition"))) {
                    hasConditions = true;
                    break;
                }
            }

            if (hasConditions) {
                // 先生成条件为true的分支
                for (JSONObject conn : outgoing) {
                    String condition = conn.getString("condition");
                    if (condition != null && !condition.startsWith("!")) {
                        groovy.append("        if (").append(condition).append(") {\n");
                        generateComponentCode(conn.getString("endElementId"),
                                components, diamonds, connections,
                                groovy, new HashSet<>(processed), loopAnalysis);
                        groovy.append("        }\n");
                    }
                }

                // 然后生成条件为false的分支
                for (JSONObject conn : outgoing) {
                    String condition = conn.getString("condition");
                    if (condition != null && condition.startsWith("!")) {
                        groovy.append("        else {\n");
                        generateComponentCode(conn.getString("endElementId"),
                                components, diamonds, connections,
                                groovy, new HashSet<>(processed), loopAnalysis);
                        groovy.append("        }\n");
                        break; // 只需要一个else分支
                    }
                }
            } else {
                // 无条件分支
                for (JSONObject conn : outgoing) {
                    generateComponentCode(conn.getString("endElementId"),
                            components, diamonds, connections,
                            groovy, new HashSet<>(processed), loopAnalysis);
                }
            }
        }
    }

    // 处理出向连接
    // 更新后的 processOutgoingConnections 方法
    private void processOutgoingConnections(String currentId,
                                            Map<String, JSONObject> components,
                                            Map<String, JSONObject> diamonds,
                                            JSONArray connections,
                                            StringBuilder groovy,
                                            Set<String> processed,
                                            LoopAnalysisResult loopAnalysis) {
        List<JSONObject> outgoing = new ArrayList<>();

        // 收集所有出向连接（只处理有效连接）
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            if (currentId.equals(conn.getString("startElementId")) &&
                    isValidElement(conn.getString("endElementId"), diamonds, components)) {
                outgoing.add(conn);
            }
        }

        // 处理所有有效出向连接
        for (JSONObject conn : outgoing) {
            generateComponentCode(conn.getString("endElementId"),
                    components, diamonds, connections,
                    groovy, new HashSet<>(processed), loopAnalysis);
        }
        //如果没有出向连接，则生成一个默认的结束代码
        if (outgoing.isEmpty()) {
            groovy.append("        return \n");
        }
    }
    // 新增方法：检查元素ID是否有效
    private boolean isValidElement(String elementId,
                                   Map<String, JSONObject> diamonds,
                                   Map<String, JSONObject> components) {
        if (elementId == null || elementId.isEmpty()) {
            return false;
        }
        return diamonds.containsKey(elementId) || components.containsKey(elementId);
    }

    /**
     * 提取子功能点groovy源码
     * @param svgElements
     * @return
     */
    private List<String> pickChildGroovySource(JSONArray svgElements) {
        List<String> sources = new ArrayList<>();
        for (int i = 0; i < svgElements.size(); i++) {
            JSONObject element = svgElements.getJSONObject(i);
            JSONArray children = element.getJSONArray("children");
            String objectType = element.getString("objectType");
            //只处理组件
            if (IBusinessConstant.NODE_TYPE_COMPONENT.equals(objectType)) {
                if (children != null && children.size() > 2) {
                    JSONObject firstChild = children.getJSONObject(2);
                    JSONObject attrs = firstChild.getJSONObject("attrs");
                    String className = attrs.getString("className");
                    //是否为租户函数（功能点），默认为否(N)
                    String isTenant = attrs.getString("isTenant");
                    if ("Y".equals(isTenant)) {
                        TenantFunctionVersion tenantFunctionVersion = tenantFunctionVersionMapper.getTenantFunctionByClassName(className);
                        if (tenantFunctionVersion != null) {
                            sources.add(tenantFunctionVersion.getGroovySource());
                        } else
                            throw new RuntimeException("未找到类：" + className + "租户组件功能点版本表或者该类已经禁用！");
                    } else {
                        SysFunction sysFunction = sysFunctionService.getSysFunctionByClassName(className);
                        if (sysFunction != null) {
                            sources.add(sysFunction.getGroovySource());
                        } else
                            throw new RuntimeException("未找到类：" + className + "系统功能表或者该类已经禁用");
                    }
                }
            }
        }
        return sources;
    }

    /**
     * 合并多个Groovy脚本的import语句（去重）
     * @param sources 原始脚本列表
     * @return 合并后的import段 + 原始代码（保持不变）
     */
    public String mergeOnlyImports(List<String> sources) {
        Set<String> imports = new LinkedHashSet<>();
        // 匹配：import [static] pkg.Class [;]
        Pattern pattern = Pattern.compile(
                "^\\s*import\\s+(?:static\\s+)?([\\w.]+(?:\\.[\\w*]+)*)\\s*;?",
                Pattern.MULTILINE
        );

        for (String source : sources) {
            Matcher matcher = pattern.matcher(source);
            while (matcher.find()) {
                // 统一补全为规范格式（带分号）
                imports.add("import " + matcher.group(1) );
            }
        }
        StringBuilder  sb = new StringBuilder();
        for (String importSeg : imports) {
            sb.append(importSeg).append("\n");
        }
        return sb.toString();
    }
    // 辅助方法：索引元素
    private void indexElements(JSONArray elements, Map<String, JSONObject> map) {
        for (int i = 0; i < elements.size(); i++) {
            JSONObject element = elements.getJSONObject(i);
            map.put(element.getString("id"), element);
        }
    }
    // 辅助方法：查找起始组件
    private String findStartComponent(JSONArray connections, Set<String> componentIds) {
        Set<String> hasIncoming = new HashSet<>();
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            hasIncoming.add(conn.getString("endElementId"));
        }
        componentIds.removeAll(hasIncoming);
        return componentIds.isEmpty() ? null : componentIds.iterator().next();
    }


    // 核心方法：递归生成组件代码
    private void generateComponentCode(String elementId,
                                       Map<String, JSONObject> components,
                                       Map<String, JSONObject> diamonds,
                                       JSONArray connections,
                                       StringBuilder groovy,
                                       Set<String> processed,
                                       LoopAnalysisResult loopAnalysis) {
        // 如果是循环起点
        if (loopAnalysis.loopStartPoints.contains(elementId)) {
            String exitCondition = loopAnalysis.loopExitConditions.get(elementId);

            groovy.append("    // 循环开始\n");
            groovy.append("    while (true) {\n");

            generateComponentBody(elementId, components, diamonds, connections,
                    groovy, processed, loopAnalysis);

            // 添加退出条件
            if (exitCondition != null) {
                groovy.append("        // 循环退出条件\n");
                groovy.append("        if (").append(exitCondition).append(") {\n");
                groovy.append("            break\n");
                groovy.append("        }\n");
            }

            groovy.append("    }\n");
            return;
        }

        // 正常处理组件
        generateComponentBody(elementId, components, diamonds, connections,
                groovy, processed, loopAnalysis);
    }


    // 辅助方法：追加参数
    private void appendParams(StringBuilder groovy, JSONArray params) {
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                JSONObject param = params.getJSONObject(i);
                groovy.append(param.getString("value"));
                if (i < params.size() - 1) groovy.append(", ");
            }
        }
    }

    /**
     * 根据类名查询组件功能点
     *
     * @param className 类名
     */
    @Override
    public TenantFunctionVersion getTenantFunctionByClassName(String className) {
        return tenantFunctionVersionMapper.getTenantFunctionByClassName(className);
    }

    /**
     * 获取简单类名，不包含包名
     * @param className
     * @return
     */
    private String getSimpleClassName(String className) {
        int lastDotIndex = className.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return className.substring(lastDotIndex + 1);
        } else {
            return className;
        }
    }
    // 辅助方法：根据条件查找连接
    private JSONObject findConnectionByCondition(List<JSONObject> connections, String condition) {
        for (JSONObject conn : connections) {
            if (condition.equals(conn.getString("condition"))) {
                return conn;
            }
        }
        return null;
    }

    // 处理出向连接（优化后的版本）

}
